package com.project.api.common;

import com.alibaba.fastjson.JSONObject;
import com.project.api.sale.controller.AccessTokenUtil;
//import com.project.api.yunshang.service.YunShang;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class Http {
    public static String TimeOut="timeOut";
    public static String ServerError="serverError";
    public static String UnknownError="unknownError";
    public static String Get(String url,String param){
        String result ="";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);

            URLConnection connection = realUrl.openConnection();

            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            connection.setConnectTimeout(3000);

            connection.connect();

            Map<String, List<String>> map = connection.getHeaderFields();

            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }

            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            if(JsonType.getJSONType(result)==JsonType.JSON_TYPE_ERROR){

            }
        } catch (Exception e) {
            System.out.println("get连接出现bug");
        }
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    public static String Post(String url,String param){
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);

            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();


            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//            if (Constants.SESSION_ID != null){
//                conn.setRequestProperty("cookie", Constants.SESSION_ID);
//            }
            conn.setConnectTimeout(3000);
            conn.setReadTimeout(3000);

            //设置为post请求
            conn.setDoOutput(true);
            conn.setDoInput(true);

            out = new PrintWriter(conn.getOutputStream());

            JSONObject jsonObject = new JSONObject();

            // 参数
            out.print(param);
            out.flush();
//            String cookieValue = conn.getHeaderField("set-cookie");//获取回话的sessionid
//            if (cookieValue != null){
//                Constants.SESSION_ID = cookieValue.substring(0, cookieValue.indexOf(";"));
//                System.out.println("session是：" + Constants.SESSION_ID);
//            }
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            System.out.println("数据buffer");
            while ((line = in.readLine()) != null) {
                result += line;
            }
            if(JsonType.getJSONType(result)==JsonType.JSON_TYPE_ERROR){

            }
        } catch (Exception e){
            if (e instanceof SocketTimeoutException){
                System.out.println("出现连接超时的情况");
                return "{'result': '"+TimeOut+"','msg':'连接超时'}";
            }else if (e instanceof FileNotFoundException){
                System.out.println("服务器内部出错");
                e.printStackTrace();
                return "{'result': '"+ServerError+"', 'msg':'服务器内部错误'}";
            }else {
                e.printStackTrace();
                return "{'result': '"+UnknownError+"', 'msg':'未知错误'}";
            }
        } finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException e){
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 用于在客户下单付款成功后调用，通知相关人员有订单下单成功
     * @param openid 用户在服务号上的id
     * @param firstData 消息的首条信息
     * @param moneySum 支付金额
     * @param productName 商品名称
     * @param remarkData 备注信息
     * @throws Exception
     */
    public static void sendOrderPayMsg(String openid, String firstData, double moneySum, String productName, String remarkData) throws Exception {

        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + AccessTokenUtil.accessToken.getAccess_token();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();


//        json方式
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("touser", openid);
        jsonParam.put("template_id", "ksTpeJzajIS8qxwnWsVta9CKlUSqjpcqueBvsvhkKnQ");

        //data数据整理
        JSONObject data = new JSONObject();
        JSONObject first = new JSONObject();
        JSONObject orderMoneySum = new JSONObject();
        JSONObject orderProductName = new JSONObject();
        JSONObject remark = new JSONObject();
        first.put("value", firstData);
        orderMoneySum.put("value", String.format("%.2f", moneySum));
        orderProductName.put("value", productName);
        remark.put("value", remarkData);

        data.put("first", first);
        data.put("orderMoneySum", orderMoneySum);
        data.put("orderProductName", orderProductName);
        data.put("Remark", remark);

        jsonParam.put("data", data);

        StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

        HttpResponse resp = client.execute(httpPost);
        if(resp.getStatusLine().getStatusCode() == 200) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }

    public static void sendDeliveryMsg(String openid, String firstData, String payTime, String productName, String totalSum, String remarkData) throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + AccessTokenUtil.accessToken.getAccess_token();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();

//        json方式
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("touser", openid);
        jsonParam.put("template_id", "QrT53oiOuNYoUNf0G0djPf1Qq646ng2DdvVmEogB2W0");

        //data数据整理
        JSONObject data = new JSONObject();
        JSONObject first = new JSONObject();
        JSONObject keyword1 = new JSONObject();
        JSONObject keyword2 = new JSONObject();
        JSONObject keyword3 = new JSONObject();
        JSONObject remark = new JSONObject();
        first.put("value", firstData);
        keyword1.put("value", payTime);
        keyword2.put("value", productName);
        keyword3.put("value", totalSum);
        remark.put("value", remarkData);

        data.put("first", first);
        data.put("keyword1", keyword1);
        data.put("keyword2", keyword2);
        data.put("keyword3", keyword3);
        data.put("remark", remark);

        jsonParam.put("data", data);

        StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

        HttpResponse resp = client.execute(httpPost);
        if(resp.getStatusLine().getStatusCode() == 200) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }

    public static void sendDeliverySubscribeMsg(String openid, String firstData, String payTime, String productName, String totalSum, String remarkData) throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/subscribe?access_token=" + AccessTokenUtil.accessToken.getAccess_token();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();

//        json方式
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("touser", openid);
        jsonParam.put("template_id", "hySUqPlbUO8xhb3QYseiht6KI8CtVb8Jb4PQXwwRjmU");

        //data数据整理
        JSONObject data = new JSONObject();
        JSONObject first = new JSONObject();
        JSONObject keyword1 = new JSONObject();
        JSONObject keyword2 = new JSONObject();
        JSONObject keyword3 = new JSONObject();
        JSONObject remark = new JSONObject();
        first.put("value", firstData);
        keyword1.put("value", payTime);
        keyword2.put("value", productName);
        keyword3.put("value", totalSum);
        remark.put("value", remarkData);

        data.put("first", first);
        data.put("keyword1", keyword1);
        data.put("keyword2", keyword2);
        data.put("keyword3", keyword3);
        data.put("remark", remark);

        jsonParam.put("title", "测试标题");
        jsonParam.put("data", "");
        jsonParam.put("scene", "100");

        StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

        HttpResponse resp = client.execute(httpPost);
        if(resp.getStatusLine().getStatusCode() == 200) {
            System.out.println("调用成功" + resp.getEntity());
        } else {
            System.out.println("调用失败");
        }
    }

    /**
     * 向目的URL发送post请求
     * @param url       目的url
     * @param params    发送的参数
     * @return  ResultVO
     */
    public static String sendPostRequest(String url, MultiValueMap<String, String> params){
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //将请求头部和参数合成一个请求
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
        //执行HTTP请求，将返回的结构使用ResultVO类格式化
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
        HttpStatus statusCode = response.getStatusCode();
        int statusCodeValue = response.getStatusCodeValue();
        HttpHeaders callbackHeaders = response.getHeaders();
        if(statusCodeValue!=200){
           return ApiResponse.Fail("连接出错");
        }
        return response.getBody();
    }
    /**
     * 向目的URL发送get请求
     * @param url       目的url
     * @return  ResultVO
     */
    public static String sendGetRequest(String url){
        MultiValueMap<String, String> params=new LinkedMultiValueMap<>();
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.GET;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //将请求头部和参数合成一个请求
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
        //执行HTTP请求，将返回的结构使用ResultVO类格式化
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
        HttpStatus statusCode = response.getStatusCode();
        int statusCodeValue = response.getStatusCodeValue();
        HttpHeaders callbackHeaders = response.getHeaders();
        if(statusCodeValue!=200){
            return ApiResponse.Fail("连接出错");
        }
        return response.getBody();
    }
    /*
     *payload方式post
     */
    public static String pPost(String url,String data){
        RestTemplate client = new RestTemplate();
        //  一定要设置header
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
//        if(YunShang.K3COOKIE!=null){
//            headers.add(HttpHeaders.COOKIE,YunShang.K3COOKIE);
//        }
        HttpEntity<String> requestEntity = new HttpEntity<String>(data, headers);
        //  执行HTTP请求
        ResponseEntity<String> response = client.postForEntity(url, requestEntity , String.class );
        HttpStatus statusCode = response.getStatusCode();
        int statusCodeValue = response.getStatusCodeValue();
        HttpHeaders callbackHeaders = response.getHeaders();
        List<String> cookies=callbackHeaders.get("Set-Cookie");
        for(int i=0;i<cookies.size();i++){
            String head=cookies.get(i);
            if(head.startsWith("kdservice-sessionid")){
//                YunShang.K3COOKIE=head;
            }
        }
        if(statusCodeValue!=200){
            return ApiResponse.Fail("连接出错");
        }
        return response.getBody();
    }

    /**
     * k3 WEBAPI GET
     * @param url
     * @param param
     * @return
     */
    public static String K3Get(String url,String param){
        MultiValueMap<String, String> params=new LinkedMultiValueMap<>();
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.GET;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //将请求头部和参数合成一个请求
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
        //执行HTTP请求，将返回的结构使用ResultVO类格式化
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
        HttpStatus statusCode = response.getStatusCode();
        int statusCodeValue = response.getStatusCodeValue();
        HttpHeaders callbackHeaders = response.getHeaders();
        if(statusCodeValue!=200){
            return ApiResponse.Fail("连接出错");
        }
        return response.getBody();
    }

    /**
     * k3 WEBAPI POST
     * @param url
     * @param params
     * @return
     */
    public static String K3Post(String url,MultiValueMap<String, String> params){
        RestTemplate client = new RestTemplate();
        //  一定要设置header
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
        //  执行HTTP请求
        ResponseEntity<String> response = client.postForEntity(url, requestEntity , String.class );
        HttpStatus statusCode = response.getStatusCode();
        int statusCodeValue = response.getStatusCodeValue();
        HttpHeaders callbackHeaders = response.getHeaders();
        if(statusCodeValue!=200){
            return ApiResponse.Fail("连接出错");
        }
        return response.getBody();
    }
}
